package com.aididi.service;

import com.aididi.constant.Constants;
import com.aididi.entity.BrokerMessageLog;
import com.aididi.entity.Order;
import com.aididi.mapper.BrokerMessageLogMapper;
import com.aididi.mapper.OrderMapper;
import com.aididi.producer.SendMessage;
import com.aididi.utils.FastJsonConvertUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Auther: zx.xu
 * @Description:
 */
@Service
public class OrderService {
    private final OrderMapper orderMappr;
    private final BrokerMessageLogMapper brokerMessageLogMapper;
    private final SendMessage orderSender;

    @Autowired
    public OrderService(OrderMapper orderMappr, BrokerMessageLogMapper brokerMessageLogMapper, SendMessage orderSender) {
        this.orderMappr = orderMappr;
        this.brokerMessageLogMapper = brokerMessageLogMapper;
        this.orderSender = orderSender;
    }

    /**
     *  创建订单
     */

    public void create(Order order) throws Exception{
        Date date = new Date();
        //业务数据入库
        this.orderMappr.insert(order);
        BrokerMessageLog messageLogVO = new BrokerMessageLog();
        messageLogVO.setMessageId(order.getMessageId());
        messageLogVO.setMessage(FastJsonConvertUtil.convertObjectToJson(order));
        messageLogVO.setStatus(Constants.OrderSendStatus.SENDING);
        messageLogVO.setTryCount(0);
        messageLogVO.setNextRetry(DateUtils.addMinutes(date,Constants.ORDER_TIMEOUT));
        messageLogVO.setCreateTime(date);
        this.brokerMessageLogMapper.insert(messageLogVO);
        //业务和消息都入库后，发送消息
        this.orderSender.sender(order);
    }
}
